package com.ljq.epidemic.component;


import com.google.gson.Gson;
import com.ljq.epidemic.bean.DataBean;
import com.ljq.epidemic.service.DataService;
import com.ljq.epidemic.util.JsonReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class DataHandler {

    private static final String URL_STR = "https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5";

    private static final String FILE_Path = "springboot-epidemic/src/temp.json";

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Autowired
    private DataService dataService;

    @PostConstruct
    public void initData(){
        System.out.println("初始化数据...");

        List<DataBean> beanList = dataList();

        //先清空数据再导入数据
        dataService.remove(null);
        dataService.saveBatch(beanList);
    }

    /**
     * 每一分钟：0 0/1 * * * ?
     * 每五分钟：0 0/5 * * * ?
     */
    @Scheduled(cron = "0 0/5 * * * ? ")
    public void updateData(){
        System.out.println("更新数据,当前时间" + dateFormat.format(new Date()));

        List<DataBean> dataBeans = dataList();

        // 先清空 再存储
        dataService.remove(null);
        dataService.saveBatch(dataBeans);
    }


    public ArrayList<DataBean> dataList() {
        Gson gson = new Gson();

//        String json = JsonReader.fromFile(FILE_Path);
        String json = JsonReader.fromURL(URL_STR);

        json = json.replaceAll("\"","\"");

        Map objectMap = gson.fromJson(json,Map.class);

        String data = (String)objectMap.get("data");

        Map dataMap = gson.fromJson(data,Map.class);

        ArrayList<Map> areaList = (ArrayList<Map>)dataMap.get("areaTree");

        ArrayList<DataBean> dataList = new ArrayList<>();

        for(Map areaMap : areaList){
            ArrayList<Map> childrenList = (ArrayList<Map>)areaMap.get("children");

            for(Map childrenMap : childrenList){
                String name = (String)childrenMap.get("name");

                Map total = (Map)childrenMap.get("total");

                double nowConfirm = (double)total.get("nowConfirm");
                double confirm = (double)total.get("confirm");
                double heal = (double)total.get("heal");
                double dead = (double)total.get("dead");

                DataBean dataBean = new DataBean();

                dataBean.setName(name);
                dataBean.setNowConfirm((int)nowConfirm);
                dataBean.setConfirm((int)confirm);
                dataBean.setHeal((int)heal);
                dataBean.setDead((int)dead);

                dataList.add(dataBean);
            }
        }

        return dataList;
    }

}
